const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');

// JWT验证中间件
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  
  if (!token) {
    return res.status(401).json({ message: '访问令牌缺失' });
  }
  
  jwt.verify(token, global.JWT_SECRET, (err, user) => {
    if (err) {
      return res.status(403).json({ message: '访问令牌无效' });
    }
    req.user = user;
    next();
  });
};

// 获取用户所有地址
router.get('/', authenticateToken, (req, res) => {
  const userId = req.user.userId;
  
  const query = 'SELECT * FROM addresses WHERE user_id = ? ORDER BY is_default DESC, created_at DESC';
  global.db.query(query, [userId], (err, results) => {
    if (err) {
      console.error('获取地址失败:', err);
      return res.status(500).json({ message: '获取地址失败' });
    }
    res.json({ message: '获取成功', addresses: results });
  });
});

// 添加新地址
router.post('/', authenticateToken, (req, res) => {
  const userId = req.user.userId;
  const { name, phone, province, city, district, detail, isDefault } = req.body;
  
  if (!name || !phone || !province || !city || !district || !detail) {
    return res.status(400).json({ message: '地址信息不完整' });
  }
  
  // 如果设为默认地址，先取消其他默认地址
  const processInsert = () => {
    const insertQuery = `
      INSERT INTO addresses (user_id, name, phone, province, city, district, detail, is_default) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `;
    
    global.db.query(insertQuery, [userId, name, phone, province, city, district, detail, isDefault ? 1 : 0], (err, result) => {
      if (err) {
        console.error('添加地址失败:', err);
        return res.status(500).json({ message: '添加地址失败' });
      }
      res.json({ message: '添加成功', addressId: result.insertId });
    });
  };
  
  if (isDefault) {
    const updateQuery = 'UPDATE addresses SET is_default = 0 WHERE user_id = ?';
    global.db.query(updateQuery, [userId], (err) => {
      if (err) {
        console.error('更新默认地址失败:', err);
        return res.status(500).json({ message: '设置默认地址失败' });
      }
      processInsert();
    });
  } else {
    processInsert();
  }
});

// 更新地址
router.put('/:id', authenticateToken, (req, res) => {
  const userId = req.user.userId;
  const addressId = req.params.id;
  const { name, phone, province, city, district, detail, isDefault } = req.body;
  
  if (!name || !phone || !province || !city || !district || !detail) {
    return res.status(400).json({ message: '地址信息不完整' });
  }
  
  // 验证地址是否属于当前用户
  const checkQuery = 'SELECT * FROM addresses WHERE id = ? AND user_id = ?';
  global.db.query(checkQuery, [addressId, userId], (err, results) => {
    if (err) {
      console.error('验证地址失败:', err);
      return res.status(500).json({ message: '验证地址失败' });
    }
    
    if (results.length === 0) {
      return res.status(404).json({ message: '地址不存在或无权限' });
    }
    
    const processUpdate = () => {
      const updateQuery = `
        UPDATE addresses 
        SET name = ?, phone = ?, province = ?, city = ?, district = ?, detail = ?, is_default = ?
        WHERE id = ? AND user_id = ?
      `;
      
      global.db.query(updateQuery, [name, phone, province, city, district, detail, isDefault ? 1 : 0, addressId, userId], (err) => {
        if (err) {
          console.error('更新地址失败:', err);
          return res.status(500).json({ message: '更新地址失败' });
        }
        res.json({ message: '更新成功' });
      });
    };
    
    if (isDefault) {
      // 如果设为默认地址，先取消其他默认地址
      const clearDefaultQuery = 'UPDATE addresses SET is_default = 0 WHERE user_id = ? AND id != ?';
      global.db.query(clearDefaultQuery, [userId, addressId], (err) => {
        if (err) {
          console.error('清除默认地址失败:', err);
          return res.status(500).json({ message: '设置默认地址失败' });
        }
        processUpdate();
      });
    } else {
      processUpdate();
    }
  });
});

// 删除地址
router.delete('/:id', authenticateToken, (req, res) => {
  const userId = req.user.userId;
  const addressId = req.params.id;
  
  // 验证地址是否属于当前用户
  const checkQuery = 'SELECT * FROM addresses WHERE id = ? AND user_id = ?';
  global.db.query(checkQuery, [addressId, userId], (err, results) => {
    if (err) {
      console.error('验证地址失败:', err);
      return res.status(500).json({ message: '验证地址失败' });
    }
    
    if (results.length === 0) {
      return res.status(404).json({ message: '地址不存在或无权限' });
    }
    
    const deleteQuery = 'DELETE FROM addresses WHERE id = ? AND user_id = ?';
    global.db.query(deleteQuery, [addressId, userId], (err) => {
      if (err) {
        console.error('删除地址失败:', err);
        return res.status(500).json({ message: '删除地址失败' });
      }
      res.json({ message: '删除成功' });
    });
  });
});

// 设置默认地址
router.put('/:id/default', authenticateToken, (req, res) => {
  const userId = req.user.userId;
  const addressId = req.params.id;
  
  // 验证地址是否属于当前用户
  const checkQuery = 'SELECT * FROM addresses WHERE id = ? AND user_id = ?';
  global.db.query(checkQuery, [addressId, userId], (err, results) => {
    if (err) {
      console.error('验证地址失败:', err);
      return res.status(500).json({ message: '验证地址失败' });
    }
    
    if (results.length === 0) {
      return res.status(404).json({ message: '地址不存在或无权限' });
    }
    
    // 先取消所有默认地址
    const clearDefaultQuery = 'UPDATE addresses SET is_default = 0 WHERE user_id = ?';
    global.db.query(clearDefaultQuery, [userId], (err) => {
      if (err) {
        console.error('清除默认地址失败:', err);
        return res.status(500).json({ message: '设置默认地址失败' });
      }
      
      // 设置新的默认地址
      const setDefaultQuery = 'UPDATE addresses SET is_default = 1 WHERE id = ? AND user_id = ?';
      global.db.query(setDefaultQuery, [addressId, userId], (err) => {
        if (err) {
          console.error('设置默认地址失败:', err);
          return res.status(500).json({ message: '设置默认地址失败' });
        }
        res.json({ message: '设置默认地址成功' });
      });
    });
  });
});

module.exports = router;
